import 'package:app/pages/news_module/video_module/video_comment_page.dart';
import 'package:app/pages/news_module/video_module/video_model.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:like_button/like_button.dart';

import 'package:share_plus/share_plus.dart';
import 'package:video_player/video_player.dart';
import 'package:get/get.dart';
import '../../../services/address.dart';
import '../../../services/dio_manager.dart';
import '../../../utils/persisten_storage.dart';
import '../news_detail_model.dart';
import '../news_model.dart';


class NewsVideoPage extends StatefulWidget {

  // NewsListModel? model;

  @override
  State<NewsVideoPage> createState() => _NewsVideoPageState();
}

class _NewsVideoPageState extends State<NewsVideoPage> {

  late VideoPlayerController _controller;

  var dura;


  VideoModel? _videoModel;


  List dataArr = [];

  void requestData()async{
      var json = await DioManager().kkRequest('${Address.videoList}',
        method: 'get',);
      VideoModel model = VideoModel.fromJson(json);
      _videoModel = model;

      dataArr.addAll(model.data!);

      setState(() {

      });

  }

  /// 请求详情
  // void requestData()async{
  //
  //   var json = await DioManager().rcRequset('${Address.newsDetail}/${widget.model!.id}',
  //     method: 'get', header: {'access_token': await PersistentStorage().getStorage('acctoken'),
  //       'user_id':await PersistentStorage().getStorage('uid'),
  //       'company_id':await PersistentStorage().getStorage('companyId')
  //     },);
  //
  //   if(json['errmsg']=='no'){
  //     // LKToast.toast(context,msg: json['message']);
  //     BotToast.showText(text: json['message']);
  //     Get.back();
  //   }
  //
  //   NewsDetailModel model = NewsDetailModel.fromJson(json);
  //
  //   _model = model;
  //   //
  //   // if(dataList[0]['my_follows']=='0'){
  //   //   _isCollection = false;
  //   //
  //   // }else{
  //   //   _isCollection = true;
  //   // }
  //
  //   setState(() {
  //
  //   });
  //
  // }
  /// 收藏请求
  /// 收藏请求
  /// 1-收藏 0-取消
  // void requestCollection(int status)async{
  //
  //   var params = {
  //     'news_id':'${widget.model!.id}',
  //     'status':status,
  //   };
  //   var json = await DioManager().rcRequset('${Address.newsCollect}',
  //       header: {'access_token': await PersistentStorage().getStorage('acctoken'),
  //         'user_id':await PersistentStorage().getStorage('uid'),
  //         'company_id':await PersistentStorage().getStorage('companyId')
  //       },
  //       bodyParams: params);
  //
  //   if(json['errmsg'] == 'ok'){
  //     BotToast.showText(text: '收藏成功');
  //     requestData();
  //     // LKToast.toast(context,msg: json['message'],position: ToastPostion.bottom);
  //   }else{
  //
  //   }
  //   setState(() {
  //
  //   });
  // }




  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    requestData();

    // print('${widget.model!.vurl}&preview=1');
    //设置视频参数 (..)是级联的意思
    _controller = VideoPlayerController.network(
      '')
      ..initialize().then((_) {
        // 确保在初始化视频后显示第一帧，直至在按下播放按钮。
        setState(() {});
      });




    //执行监听，只要有内容就会刷新
    _controller.addListener(() {
      setState(() {
        //进度条的播放进度，用当前播放时间除视频总长度得到
        dura=_controller.value.position.inSeconds/
            _controller.value.duration.inSeconds;
      });
    });

  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {


    return Scaffold(
      body: Container(
        color: Colors.black,
        child: PageView.builder(
          /// 上下滑动
          scrollDirection: Axis.vertical,

          itemBuilder: (BuildContext context, int index) {

            VideoListModel _model = dataArr[index];


            // _controller = VideoPlayerController.network(
            //     '${_model.vurl}&preview=1')
            //   ..initialize().then((_) {
            //     // 确保在初始化视频后显示第一帧，直至在按下播放按钮。
            //     setState(() {});
            //   });

            return VideoPlayPage(_model.vurl,_model);
          },itemCount:dataArr.length,),
      ),
    );
  }
}


class VideoPlayPage extends StatefulWidget {


  var url;

  VideoListModel _model;


  VideoPlayPage(this.url,this._model);

  @override
  State<VideoPlayPage> createState() => _VideoPlayPageState();
}

class _VideoPlayPageState extends State<VideoPlayPage> {

  late VideoPlayerController _controller;

  var dura;

  NewsDetailModel? _detailModel;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    requestData();
    // print('${widget.model!.vurl}&preview=1');
    //设置视频参数 (..)是级联的意思
    _controller = VideoPlayerController.network(
        '${widget.url}')
      ..initialize().then((_) {
        // 确保在初始化视频后显示第一帧，直至在按下播放按钮。
        setState(() {});
      });




    //执行监听，只要有内容就会刷新
    _controller.addListener(() {
      setState(() {
        //进度条的播放进度，用当前播放时间除视频总长度得到
        dura=_controller.value.position.inSeconds/
            _controller.value.duration.inSeconds;
      });
    });
  }

  /// 请求详情
  void requestData()async{

    var json = await DioManager().kkRequest('${Address.newsDetail}/${widget._model.id}',
      method: 'get', header: {'access_token': await PersistentStorage().getStorage('acctoken'),
        'user_id':await PersistentStorage().getStorage('uid'),
        'company_id':await PersistentStorage().getStorage('companyId')
      },);

    if(json['errmsg']=='no'){
      // LKToast.toast(context,msg: json['message']);
      BotToast.showText(text: json['message']);
      Get.back();
    }

    NewsDetailModel model = NewsDetailModel.fromJson(json);

    _detailModel = model;


    setState(() {

    });

  }
  /// 收藏请求
  /// 1-收藏 0-取消
  void requestCollection(int status)async{

    var params = {
      'news_id':'${widget._model.id}',
      'status':status,
    };
    var json = await DioManager().kkRequest('${Address.newsCollect}',
        header: {'access_token': await PersistentStorage().getStorage('acctoken'),
          'user_id':await PersistentStorage().getStorage('uid'),
          'company_id':await PersistentStorage().getStorage('companyId')
        },
        bodyParams: params);

    if(json['errmsg'] == 'ok'){
      BotToast.showText(text: json['message']);

      // LKToast.toast(context,msg: json['message'],position: ToastPostion.bottom);
    }else{

    }
    setState(() {

    });
  }
  /// 点赞
  /// 1-dianza 2-quxiao
  void requestPraise(int status)async{

    var params = {
      'news_id':'${widget._model.id}',
      'status':status,
    };
    var json = await DioManager().kkRequest('${Address.newsPraise}',
        bodyParams: params);

    if(json['errmsg'] == 'ok'){
      BotToast.showText(text: json['message']);

      // LKToast.toast(context,msg: json['message'],position: ToastPostion.bottom);
    }else{

    }
    setState(() {

    });
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,

      children: [
        Container(
          child: Text(''),
        ),

        Container(

          height: 480,
          // color: Colors.yellow,
          child: Stack(
            clipBehavior: Clip.none,
            alignment: Alignment.center,
            children: [
              Center(
                child: Container(
                  height: 550,
                  color: Colors.black54,
                  child: _controller.value.isInitialized
                      ? AspectRatio(
                      aspectRatio: _controller.value.aspectRatio,
                      child: VideoPlayer(_controller)
                  )
                      : Container(),
                  // child: ChewiePlayerPage('http://www.zyfchina.com/templates/default/vedio/zyf.mp4'),
                ),
              ),
              GestureDetector(
                child: Container(
                  child:Visibility(
                    visible:_controller.value.isPlaying?false:true,
                    maintainAnimation: true,
                    maintainSize: true,
                    maintainState: true,
                    maintainInteractivity: true,
                    child: Image.asset('images/play.png',width: 55,height: 55,
                      alignment: Alignment.centerLeft,),
                  ),),

                onTap: (){
                  setState(() {
                    _controller.value.isPlaying
                        ? _controller.pause()
                        : _controller.play();
                  });
                },
              ),

              Positioned(
                top: 150,right: 10,
                child: Align(
                  alignment: Alignment.topRight,
                  child: Container(
                    height: 350,
                    width: 50,
                    // color: Colors.red,
                    padding: EdgeInsets.only(bottom: 25),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        Container(),
                        GestureDetector(
                          child: Column(
                            children: [
                              LikeButton(

                                onTap: (bool isLiked)async{
                                  // print('dianzan');
                                  requestPraise(1);
                                  requestData();
                                  return !isLiked;
                                },
                                likeBuilder: (bool isLiked){
                                return _detailModel?.data?.is_praise==true?
                                Image.asset('images/video_zan.png',color: Colors.red,)
                                    :Image.asset('images/video_zan.png');
                                },
                              ),
                              // Image.asset('images/zan.png',width: 30,height: 30,color: Colors.white,),
                              _detailModel==null?Text('0',style: TextStyle(fontSize: 12,color: Colors.white),):  Container(
                                margin: EdgeInsets.only(right: 3),
                                child:Text('${_detailModel?.data?.praises}',style: TextStyle(fontSize: 12,color: Colors.white),),
                              )
                            ],
                          ),
                          onTap: (){
                          },
                        ),
                        GestureDetector(
                          child: Column(
                            children: [
                              Image.asset('images/pinglun.png',width: 30,height: 30,
                                color:_detailModel?.data?.newsproperty_commtf==false?Colors.grey:Colors.white,),
                            _detailModel==null?Text('0',style: TextStyle(fontSize: 12,color: Colors.white),):Text('${_detailModel?.data?.comments}',style: TextStyle(fontSize: 12,color: _detailModel?.data?.newsproperty_commtf==false?Colors.grey:
                              Colors.white),),
                            ],
                          ),
                          onTap: (){
                            if(_detailModel?.data?.newsproperty_commtf==false){
                              BotToast.showText(text: '此内容不能评论');
                              return;
                            }
                            Get.bottomSheet(VideoCommentPage(widget._model.id));
                          },
                        ),
                        GestureDetector(
                          child:  Column(
                            children: [
                              _detailModel?.data?.is_collect==false?
                              Image.asset('images/viodecollection_icon.png',width: 30,height: 30,color: Colors.white,):
                              Image.asset('images/viodecollection_icon.png',width: 30,height: 30,color: Colors.orange,),
                              _detailModel==null?Text('0',style: TextStyle(fontSize: 12,color: Colors.white),): Text('${_detailModel?.data?.collects}',style: TextStyle(fontSize: 12,color: Colors.white),),

                            ],
                          ),
                          onTap: (){
                            if(_detailModel?.data?.is_collect==true){
                              requestCollection(0);
                              requestData();
                            }else{
                              requestCollection(1);
                              requestData();
                            }
                          },
                        ),

                        GestureDetector(
                          child: Column(
                            children: [
                              Image.asset('images/zhuanfa_icon.png',width: 35,height: 35,color: Colors.white,),
                              Text('分享',style: TextStyle(fontSize: 12,color: Colors.white),),
                            ],
                          ),
                          onTap: (){
                            Share.share('DTCloud-MES \n ${widget._model.vurl}&preview=1');

                          },
                        )
                      ],
                    ),
                  ),
                ),),

            ],
          ),
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(

              margin: EdgeInsets.only(left: 15,right: 15,bottom: 0),
              child: Row(
                children: [
                  CircleAvatar(
                    backgroundColor: Colors.white,
                    radius: 15,
                    backgroundImage: NetworkImage(
                      '${Address.homeHost}${widget._model.header_img}'
                    ),
                    // child:Image.network('${Address.homeHost}${widget._model.header_img}') ,
                  ),
                  SizedBox(width: 5,),
                  Text('${widget._model.author!}',style: TextStyle(color: Colors.white,fontSize: 13,
                      fontWeight: FontWeight.w500
                  ),),
                ],
              )
            ),

            Container(

              margin: EdgeInsets.only(top: 5,left: 15,right: 15,bottom: 0),
              child:Text('${widget._model.title}',style: TextStyle(color: Colors.white70,fontSize: 13,
                  fontWeight: FontWeight.w400
              ),),
            ),
            Container(
              decoration:  BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(5.0)),
                // color: Colors.red
              ),
              alignment: Alignment.center,
              clipBehavior: Clip.antiAliasWithSaveLayer,
              height: 7,
              margin: EdgeInsets.only(left: 15,right: 15,bottom: 5),
              width: Get.width,
              child: VideoProgressIndicator(
                _controller,
                allowScrubbing: true,
                colors: VideoProgressColors(
                    backgroundColor: Colors.white30,
                    bufferedColor: Colors.redAccent,
                    playedColor: Colors.white
                ),),
            ),

            Container(
              margin: EdgeInsets.only(left: 10),
              height: 45,
              width: Get.width,
              color: Colors.transparent,
              child: Row(
                children: [
                  IconButton(onPressed: (){
                    Get.back();
                  }, icon: Icon(Icons.arrow_back_ios,color: Colors.white,size: 20,))
                ],
              ),
            )
          ],
        )
        // Text(_controller.value.toString(),style: TextStyle(color: Colors.yellow),),

      ],
    );
  }
}
